package org.xxpay.pay.channel.abcpay;

import com.abc.pay.client.ebus.PaymentResult;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.util.RequestUtils;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayNotify;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: pangxiaoyu
 * @date: 2019年12月24日10:33:01
 * @description: 农行支付回调
 */
@Service
public class AbcpayPayNotifyService extends BasePayNotify {

    private static final MyLog _log = MyLog.getLog(AbcpayPayNotifyService.class);
    private static final String logPrefix = "【处理"+ AbcpayConfig.CHANNEL_NAME+"支付回调】";

    @Override
    public String getChannelName() {
        return AbcpayConfig.CHANNEL_NAME;
    }

    @Override
    public JSONObject doNotify(Object notifyData) {
        _log.info("====== 开始处理农行支付回调通知 ======");
        HttpServletRequest request = (HttpServletRequest) notifyData;
        JSONObject retObj = buildRetObj();
        Map<String, String> payContext = new HashMap();

        String respString = AbcpayConfig.RETURN_VALUE_ERROR;
        try {
            PayOrder payOrder = verifyPayParams(request, payContext);
            if( payOrder == null ) { //验证参数失败
                retObj.put(PayConstant.RESPONSE_RESULT, AbcpayConfig.RETURN_VALUE_ERROR);
                return retObj;
            }
            //订单已经支付完成
            if(payOrder.getStatus() == PayConstant.PAY_STATUS_SUCCESS || payOrder.getStatus() == PayConstant.PAY_STATUS_COMPLETE){
                retObj.put(PayConstant.RESPONSE_RESULT, AbcpayConfig.RETURN_VALUE_SUCCESS);
                return retObj;
            }

            String channelOrderNo =payContext.get("queryId"); //上游订单号
            //上游通知 状态
            int updatePayOrderRows = commonService.payOrderService.updateStatus4Success(payOrder.getPayOrderId(), channelOrderNo);
            if (updatePayOrderRows != 1) {
                _log.error("{}更新支付状态失败,将payOrderId={},更新payStatus={}失败", logPrefix, payOrder.getPayOrderId(), PayConstant.PAY_STATUS_SUCCESS);
                retObj.put(PayConstant.RESPONSE_RESULT, "处理订单失败");
                return retObj;
            }
            _log.error("{}更新支付状态成功,将payOrderId={},更新payStatus={}成功", logPrefix, payOrder.getPayOrderId(), PayConstant.PAY_STATUS_SUCCESS);
            payOrder.setStatus(PayConstant.PAY_STATUS_SUCCESS);

            // 业务系统后端通知
            baseNotify4MchPay.doNotify(payOrder, true);

            _log.info("====== 完成处理农行支付回调通知 ======");
            respString = AbcpayConfig.RETURN_VALUE_SUCCESS;
        } catch (Exception e) {
            _log.error(e, logPrefix + "处理异常");
        }
        retObj.put(PayConstant.RESPONSE_RESULT, respString);
        return retObj;
    }

    /**
     * 验证农行支付通知参数
     * @return
     */
    public PayOrder verifyPayParams(HttpServletRequest request, Map<String, String> payContext) {

        JSONObject jsonParam = RequestUtils.getJsonParam(request, false);
        String msg = jsonParam.getString("MSG");
        PaymentResult tResult;
        try {
            //获取回调参数
            tResult = new PaymentResult(msg);
            //支付成功
            if (tResult.isSuccess()) {
                String trxType = tResult.getValue("TrxType");
                String orderNo = tResult.getValue("OrderNo");
                String amount = tResult.getValue("Amount");
                String batchNo = tResult.getValue("BatchNo");
                String voucherNo = tResult.getValue("VoucherNo");
                String hostDate = tResult.getValue("HostDate");
                String hostTime = tResult.getValue("HostTime");
                String merchantRemarks = tResult.getValue("MerchantRemarks");
                String notifyType = tResult.getValue("NotifyType");
                String iRspRef = tResult.getValue("iRspRef");
                String bank_type = tResult.getValue("bank_type");
                String thirdOrderNo = tResult.getValue("ThirdOrderNo");
                _log.info("[{}]trxType={}, orderNo={}, amount={}, batchNo={}, voucherNo={}, hostDate={}, hostTime={}, merchantRemarks={}, notifyType={}, iRspRef={}, bank_type={}, thirdOrderNo={}",
                        logPrefix, trxType, orderNo, amount, batchNo, voucherNo, hostDate, hostTime, merchantRemarks, notifyType, iRspRef, bank_type, thirdOrderNo);
                // 查询payOrder记录
                String payOrderId = orderNo;
                PayOrder payOrder = commonService.payOrderService.findByPayOrderId(payOrderId);
                if (payOrder == null) {
                    _log.error("Can't found payOrder form db. payOrderId={}, ", payOrderId);
                    return null;
                }
                // 验证金额
                String notifyAmount = AmountUtil.convertDollar2Cent(amount);
                if (!payOrder.getAmount().toString().equals(notifyAmount)){
                    _log.error("金额不一致！(分) orderAmount={}, notifyAmount={}", payOrder.getAmount(), notifyAmount);
                    return null;
                }
                payContext.put("queryId", iRspRef);
                return payOrder;
            } else {
                _log.info("{}错误编码：{}， 错误信息：{}", logPrefix, tResult.getReturnCode(), tResult.getErrorMessage());
                return null;
            }

        } catch (Exception e) {
            _log.error(e, e.getMessage());
        }
        return null;
    }
}
